import { FC, useEffect, useState } from "react";
import { Modal, List, Spin, Empty, Input, DatePicker, Button } from "antd";
import { GetFullMessageHistory } from "@/api/xhr/message";
import { getStoreItem } from "@/util/storage";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import ChatItem from "./ChatItem";
import type { BaseMessage, FriendMessage } from "@/api/xhr/message";

const { Search } = Input;
const { RangePicker } = DatePicker;

interface ChatHistoryProps {
  visible: boolean;
  onClose: () => void;
  chatId: number; // 聊天ID（好友ID或群组ID）
  chatType: "friend" | "group"; // 聊天类型
  chatName: string; // 聊天名称
}

const ChatHistory: FC<ChatHistoryProps> = ({
  visible,
  onClose,
  chatId,
  chatType,
  chatName
}) => {
  const userinfo = JSON.parse(getStoreItem("userinfo"));
  const userId = userinfo?.id;
  
  const [loading, setLoading] = useState(false);
  const [messages, setMessages] = useState<(BaseMessage<FriendMessage & { isme: boolean }> | (BaseMessage<null> & { isme: boolean }))[]>([]);
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);
  const [keyword, setKeyword] = useState("");
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
  const [pageNum, setPageNum] = useState(1);
  const [messageSize] = useState(20);
  
  // 加载聊天记录
  const loadChatHistory = async (page = 1, reset = false) => {
    if (loading) return;
    
    setLoading(true);
    try {
      const res = await GetFullMessageHistory({
        messageId: chatId,
        type: chatType,
        userId,
        pageNum: page,
        messageSize
      });
      
      if (res.statusCode === 200) {
        const formattedMessages = res.data.list.map(item => ({
          ...item,
          isme: item.id === userId
        }));
        
        if (reset) {
          setMessages(formattedMessages);
        } else {
          setMessages(prev => [...prev, ...formattedMessages]);
        }
        
        setTotal(res.data.total);
        setHasMore(res.data.hasMore);
        setPageNum(page);
      }
    } catch (error) {
      console.error("加载聊天记录失败:", error);
    } finally {
      setLoading(false);
    }
  };
  
  // 首次加载
  useEffect(() => {
    if (visible && chatId) {
      loadChatHistory(1, true);
    }
  }, [visible, chatId, chatType]);
  
  // 搜索功能
  const handleSearch = (value: string) => {
    setKeyword(value);
    // 重新加载第一页
    loadChatHistory(1, true);
  };
  
  // 日期筛选
  const handleDateChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
    setDateRange(dates);
    // 重新加载第一页
    loadChatHistory(1, true);
  };
  
  // 加载更多
  const handleLoadMore = () => {
    if (hasMore && !loading) {
      loadChatHistory(pageNum + 1);
    }
  };
  
  // 消息过滤（关键词搜索）
  const filteredMessages = keyword
    ? messages.filter(msg => 
        msg.content && msg.content.toLowerCase().includes(keyword.toLowerCase())
      )
    : messages;
  
  // 日期过滤
  const dateFilteredMessages = dateRange && dateRange[0] && dateRange[1]
    ? filteredMessages.filter(msg => {
        const msgDate = dayjs(msg.createdAt);
        return dateRange[0] && dateRange[1] && msgDate.isAfter(dateRange[0]) && msgDate.isBefore(dateRange[1].add(1, "day"));
      })
    : filteredMessages;
  
  return (
    <Modal
      title={`${chatName} 的聊天记录`}
      open={visible}
      onCancel={onClose}
      footer={null}
      width={700}
      styles={{
        body: { padding: 0, overflow: "hidden" }
      }}
    >
      <div className="px-6 py-4 border-b border-gray-200">
        <div className="flex justify-between items-center flex-wrap gap-2">
          <Search
            placeholder="搜索消息内容"
            onSearch={handleSearch}
            style={{ width: 220 }}
          />
          <RangePicker 
            onChange={handleDateChange} 
            placeholder={["开始日期", "结束日期"]} 
          />
        </div>
      </div>

      <div className="px-6 py-4" style={{ maxHeight: "60vh", overflowY: "auto" }}>
        {dateFilteredMessages.length > 0 ? (
          <List
            dataSource={dateFilteredMessages}
            renderItem={item => (
              item.messageSendType ? (
                <div className="mb-3">
                  <ChatItem
                    key={item.id + "-" + new Date(item.createdAt).getTime()}
                    isMe={item.isme}
                    message={item.content}
                    avatar={item.avatar}
                    messagetype={item.messageType}
                    showTime
                    time={dayjs(item.createdAt).format("YYYY-MM-DD HH:mm:ss")}
                  />
                </div>
              ) : (
                <p
                  key={item.id + "-system-" + new Date(item.createdAt).getTime()}
                  className="text-center text-[10px] text-gray-400 my-2"
                >
                  {item.content}
                </p>
              )
            )}
            loadMore={
              hasMore ? (
                <div className="text-center mt-4 mb-2">
                  <Button onClick={handleLoadMore} loading={loading}>
                    加载更多
                  </Button>
                </div>
              ) : (
                <div className="text-center text-gray-400 my-4">
                  {total > 0 ? "没有更多消息了" : ""}
                </div>
              )
            }
          />
        ) : (
          <Empty description={loading ? "加载中..." : "没有找到消息记录"} />
        )}
        
        {loading && messages.length === 0 && (
          <div className="text-center py-10">
            <Spin>
              <div className="h-20 flex items-center justify-center">
                <p className="text-gray-400">加载中...</p>
              </div>
            </Spin>
          </div>
        )}
      </div>
    </Modal>
  );
};

export default ChatHistory; 